package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//@RestController // @ResponseBody 底层：jackson.jar  + @Controller  ResponseBody :第一个是将字符串直接输出到页面， 第二个 将返回的对象变为json
@Controller
@RequestMapping("api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${app_id}")
    private String app_id;

    //  http://api.gmall.com/api/payment/alipay/submit/44
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String aliPay(@PathVariable Long orderId){
        //  调用服务层方法
        String form = null;
        try {
            form = this.alipayService.createaliPay(orderId);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //  将form 输出到页面.
        return form;
    }

    //  同步回调地址.
    // http://api.gmall.com/api/payment/alipay/callback/return
    @GetMapping("callback/return")
    public String callbackReturn(){
        //  重定向到web-all中的控制器，
        //  http://payment.gmall.com/pay/success.html
        return "redirect:"+ AlipayConfig.return_order_url;
    }

    //  异步回调。 http://rjsh38.natappfree.cc 需要使用内网穿透
    //  https://商家网站通知地址?voucher_detail_list=[{"amount":"0.20","merchantContribute":"0.00","name":"5折券","otherContribute":"0.20","type":"ALIPAY_DISCOUNT_VOUCHER","voucherId":"2016101200073002586200003BQ4"}]&fund_bill_list=[{"amount":"0.80","fundChannel":"ALIPAYACCOUNT"},{"amount":"0.20","fundChannel":"MDISCOUNT"}]&subject=PC网站支付交易&trade_no=2016101221001004580200203978&gmt_create=2016-10-12 21:36:12&notify_type=trade_status_sync&total_amount=1.00&out_trade_no=mobile_rdm862016-10-12213600&invoice_amount=0.80&seller_id=2088201909970555&notify_time=2016-10-12 21:41:23&trade_status=TRADE_SUCCESS&gmt_payment=2016-10-12 21:37:19&receipt_amount=0.80&passback_params=passback_params123&buyer_id=2088102114562585&app_id=2016092101248425&notify_id=7676a2e1e4e737cff30015c4b7b55e3kh6& sign_type=RSA2&buyer_pay_amount=0.80&sign=***&point_amount=0.00
    //  @RequestParam Map<String,String> paramMap 将url 路径上的参数变为Map 集合.
    //  http://rjsh38.natappfree.cc/api/payment/alipay/callback/notify
    @PostMapping("callback/notify")
    public String callBackNotify(@RequestParam Map<String,String> paramMap){
        //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //  获取参数中的out_trade_no;
        String outTradeNo = paramMap.get("out_trade_no");
        //  获取参数中的total_amount
        String totalAmount = paramMap.get("total_amount");
        //  获取参数中的app_id
        String appId = paramMap.get("app_id");
        //  获取参数中的trade_status
        String tradeStatus = paramMap.get("trade_status");
        //  获取参数中的notify_id
        String notifyId = paramMap.get("notify_id");

        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //  out_trade_no total_amount app_id
            //  验证out_trade_no 一致.
            PaymentInfo paymentInfoQuery =  this.paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
            //  项目上线： paymentInfoQuery.getTotalAmount().compareTo(new BigDecimal(totalAmount))!=0
            if (paymentInfoQuery==null || new BigDecimal("0.01").compareTo(new BigDecimal(totalAmount))!=0
                || !appId.equals(app_id)){
                //  返回失败.
                return "failure";
            }
            //  这个东西存储到缓存; setnx setex 24 小时 22 分钟
            //  set key value ex/px timeout nx/xx 第一次异步回调 notifyId 有数据. result = true;
            Boolean result = this.redisTemplate.opsForValue().setIfAbsent(notifyId, notifyId, 1462 * 60, TimeUnit.SECONDS);
            if (!result){
                //  说明缓存中有数据.
                return "failure";
            }
            //  获取到支付状态.
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                //  支付成功了. 修改交易记录状态.
                this.paymentService.paySuccess(outTradeNo,PaymentType.ALIPAY.name(),paramMap); // 正常处理了，更新订单状态.
                return "success";
            }
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
        return "";
    }

    //  退款接口：
    @GetMapping("refund/{orderId}")
    @ResponseBody
    public Boolean refund(@PathVariable Long orderId){

        //  调用服务层的方法.
        Boolean result = this.alipayService.refund(orderId);
        //  返回；
        return result;
    }

    //  关闭支付宝交易接口.
    @GetMapping("closePay/{orderId}")
    @ResponseBody
    public Boolean closePay(@PathVariable Long orderId){
        Boolean result = this.alipayService.closePay(orderId);
        return result;
    }

    //  查询交易记录:
    @GetMapping("checkPayment/{orderId}")
    @ResponseBody
    public Boolean checkPayment(@PathVariable Long orderId){
        //  调用服务层方法.
        return this.alipayService.checkPayment(orderId);
    }

    //  查询交易记录接口：
    @GetMapping("getPaymentInfo/{outTradeNo}")
    @ResponseBody
    public PaymentInfo getPaymentInfo(@PathVariable String outTradeNo){
        PaymentInfo paymentInfo = this.paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
        if (paymentInfo!=null){
            return paymentInfo;
        }else {
            return null;
        }
    }



}
